<?php

namespace App\Http\Controllers\BuyProcess;

use App\Http\Controllers\Component\MasterResponseController;
use App\Http\Requests\BuyProcess\OrderRequest;
use App\Model\ChinaProvince;
use App\Model\Goods;
use App\Model\Order;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Cache;
use Webpatser\Uuid\Uuid;

class PayController extends MasterResponseController
{
    public function index($id)
    {
        $order = Order::leftJoin('goods_v', 'orders.goods_id', 'goods_v.id')
            ->leftJoin('china_region', 'china_region.town_id', 'orders.town_id')
            ->select('orders.*',
                'china_region.province_name as province',
                'china_region.province_id as province_id',
                'china_region.city_name as city',
                'china_region.city_id as city_id',
                'china_region.county_name as county',
                'china_region.county_id as county_id',
                'china_region.town_name as region',
                'china_region.town_id as town_id',
                'goods_v.name as goods_name',
                'goods_v.author as author',
                'goods_v.price as price',
                'goods_v.size as size',
                'goods_v.genre as genre',
                'goods_v.imgUrl as imgUrl')
            ->where('orders.id', $id)
            ->first();

        $provinces = ChinaProvince::all();

        $data = array(
            'order' => $order,
            'provinces' => $provinces
        );
        return view('buy_process.pay', compact('data'));
    }

    //修改地址信息
    public function changeOrderAddress(OrderRequest $request)
    {
        Order::where('id', $request['id'])
            ->update([
                'name' => $request['name'],
                'phone' => $request['phone'],
                'town_id' => $request['town_id'],
                'detail_address' => $request['detail_address'],
            ]);

        return parent::success('地址信息已修改');
    }

    //支付
    public function pay(Request $request)
    {
        $key = $request['goods_id'];
        $ttl = 30000;
        //获取Redis实例 并指定连接为redis-order
        $redis = Redis::connection('redis-order');
        $random=Uuid::generate(4); //生成一个UUID作为当前锁的标记

        //$key 加锁的键
        // $random 当前应用锁标记
        //  【px 时间以毫秒计算 ex 时间以秒计算】
        //nx 只在键不存在时，才对键进行设置操作。 SET key value NX 效果等同于 SETNX key value 加锁的关键。
        // xx与nx相反 只在键存在时，才对键进行设置操作。
        //尝试获取锁10000毫秒 即10秒          //尝试加锁10钞钟
        $ok = $redis->set($key, $random,  'px' , $ttl,'nx');
//        $lock = Cache::lock($key, $ttl);
        //如果获取到锁 则进行支付
        if ($ok) {
            //获取当前作品状态 1代表可销售 2代码已销售
            //如果当前作品状态为1 则将订单状态变为已支付 将作品状态改为2-已销售
            $orderStatus=Order::where('id',$request['id'])->value('status');
            if($orderStatus!=0){
                //释放锁之前对当前锁标记进行判断
                //防止操作在锁时间内未完成 锁自己删除后其他应用获取到锁 从而删除其他应用的锁
                //如果此锁标记与当前应用标记一致则释放锁
                if ($redis->get($key) == $random) {
                    $redis->del($key);
                }
                return parent::error('该订单已支付，请勿重复支付！');
            }
            if ($orderStatus==5){
                //释放锁
                if ($redis->get($key) == $random) {
                    $redis->del($key);
                }
                return parent::error('对不起，您的订单已超时！');
            }

            $status=Goods::where('id',$request['goods_id'])->value('status');
            if ($status==1){
                $time=Carbon::now();
                Order::where('id', $request['id'])
                    ->update([
                        'status' => 1,
                        'pay_time'=>$time
                    ]);
                Goods::where('id',$request['goods_id'])
                    ->update([
                        'status'=>2
                    ]);
                //释放锁
                if ($redis->get($key) == $random) {
                    $redis->del($key);
                }
                return parent::success('支付成功！');
            }else{
                //释放锁
                if ($redis->get($key) == $random) {
                    $redis->del($key);
                }
              return parent::error('该商品已被其他用户订购!');
            }
        } else {
            return parent::error('服务器繁忙或该商品已被其他用户订购！,请稍后再试');
        }

    }
}
